/**
 * Created by mhy on 2018/6/30.
 */
import axios from 'axios'
import qs from 'querystring'
import {baseURL} from './baseURL'
// axios.defaults.timeout = 10000 // 定义超时为10s
export function get (path = '', options = {}, head = {}, server = 1) {
  axios.defaults.baseURL = baseURL
  // options['token'] = localStorage.getItem('token')
  head['token'] = localStorage.getItem('token')
  return new Promise(function (resolve, reject) {
    axios.get(path, {
      params: options,
      headers: head
    }).then(function (data) {
      if (data.data && data.data.error == 0) {
        resolve(data.data)
      } else {
        reject(data.data.desc)
      }
    }).catch(function (err) {
      if (navigator.onLine) {
        if (err.length > 60) {
          err = '服务器故障'
          reject(err)
        } else {
          reject(err)
        }
      } else {
        err = '网络异常，请检查网络后重试'
        reject(err)
      }
    })
  })
}

export function post (path = '', options = {}, head = {}, server = 1) {
  axios.defaults.baseURL = baseURL
  if(localStorage.getItem('token')){
    head['token'] = localStorage.getItem('token')
  }
  if(localStorage.getItem('userid') && !options['userid']){
    options['userid'] = localStorage.getItem('userid')
  }
  for (var key in head) {
    axios.defaults.headers.common[key] = head[key]
  }
  return new Promise(function (resolve, reject) {
    axios.post(path, options)
      .then(function (data) {
        if (data.data && data.data.error == 0) {
          resolve(data.data)
        } else {
          reject(data.data.desc)
        }
      }).catch(function (err) {
      if (navigator.onLine && err.length > 60) {
        if (err.length > 60) {
          err = '服务器故障'
          reject(err)
        } else {
          reject(err)
        }
      } else {
        err = '网络异常，请检查网络后重试'
        reject(err)
      }
    })
  })
}

export function uploadimg (path = '',options = FormData, head = {}, server = 1){
  axios.defaults.baseURL = baseURL
  for (var key in head) {
    axios.defaults.headers.common[key] = head[key]
  }
  return new Promise(function (resolve, reject) {
    axios.post(path, options)
      .then(function (data) {
        if (data.data && data.data.error == 0) {
          resolve(data.data)
        } else {
          reject(data.data.desc)
        }
      }).catch(function (err) {
      if (navigator.onLine && err.length > 60) {
        if (err.length > 60) {
          err = '服务器故障'
          reject(err)
        } else {
          reject(err)
        }
      } else {
        err = '网络异常，请检查网络后重试'
        reject(err)
      }
    })
  })
}
